package com.updesignsz.admin.service;

import com.updesignsz.admin.mapper.RoleFunctionMapper;
import com.updesignsz.admin.mapper.RoleMapper;
import com.updesignsz.commom.entity.Role;
import com.updesignsz.commom.entity.RoleFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * TODO
 * Created User: lx
 * Date: 2020/4/29 15:22
 */
@Service
public class RoleService {
    @Autowired private RoleMapper roleMapper;
    @Autowired private RoleFunctionMapper roleFunctionMapper;

    public List<Role> listAll() {
        return roleMapper.listAll();
    }

    public void deleteRole(Integer id) {
        roleMapper.deleteRole(id);
    }

    public Role getByRoleId(Integer roleId) {
        return roleMapper.getByRoleId(roleId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveRole(Role role) {
         roleMapper.saveRole(role);

         if (role.getId() != null) {
             setRoleFunvtion(role);
         }
    }


    private void setRoleFunvtion(Role role) {
        for (RoleFunction roleFunction : role.getRoleFunctions()) {
            roleFunction.setRoleId(role.getId());
        }
        roleFunctionMapper.deleteRoleFunction(role.getId());


        roleFunctionMapper.batchInsert(role.getRoleFunctions());

    }
}
